// 产品管理页面JavaScript
class ProductsApp {
    constructor() {
        this.baseURL = '';
        this.currentPage = 1;
        this.pageSize = 10;
        this.totalPages = 0;
        this.totalItems = 0;
        this.currentProducts = [];
        this.selectedProducts = new Set();
        this.sortColumn = '';
        this.sortDirection = 'asc';
        this.currentFilters = {};
        this.init();
    }

    init() {
        this.bindEvents();
        this.updateCurrentTime();
        this.loadProducts();
        
        // 更新时间
        setInterval(() => this.updateCurrentTime(), 1000);
    }

    bindEvents() {
        // 搜索事件
        const searchInput = document.getElementById('productSearch');
        if (searchInput) {
            searchInput.addEventListener('keypress', (e) => {
                if (e.key === 'Enter') {
                    this.searchProducts();
                }
            });
        }

        // 筛选事件
        const categoryFilter = document.getElementById('categoryFilter');
        if (categoryFilter) {
            categoryFilter.addEventListener('change', () => {
                this.applyFilters();
            });
        }

        const statusFilter = document.getElementById('statusFilter');
        if (statusFilter) {
            statusFilter.addEventListener('change', () => {
                this.applyFilters();
            });
        }

        // 表单提交事件
        const productForm = document.getElementById('productForm');
        if (productForm) {
            productForm.addEventListener('submit', (e) => {
                e.preventDefault();
                this.saveProduct(new FormData(e.target));
            });
        }
    }

    updateCurrentTime() {
        const now = new Date();
        const timeString = now.toLocaleString('zh-CN');
        const timeElement = document.getElementById('currentTime');
        if (timeElement) {
            timeElement.textContent = timeString;
        }
    }

    // API调用函数
    async apiCall(endpoint, options = {}) {
        try {
            const response = await fetch(`${this.baseURL}${endpoint}`, {
                headers: { 'Content-Type': 'application/json', ...options.headers },
                ...options
            });
            
            const data = await response.json();
            if (!response.ok) throw new Error(data.message || `HTTP错误! 状态: ${response.status}`);
            return data;
        } catch (error) {
            console.error('API调用失败:', error);
            this.showToast(`请求失败: ${error.message}`, 'error');
            throw error;
        }
    }

    // 加载产品数据
    async loadProducts() {
        try {
            const response = await this.apiCall('/api/products');
            this.currentProducts = response.data || [];
            this.totalItems = this.currentProducts.length;
            this.totalPages = Math.ceil(this.totalItems / this.pageSize);
            
            this.renderProductsTable();
            this.updatePagination();
            this.updateStatistics();
        } catch (error) {
            console.error('加载产品失败:', error);
            document.getElementById('productsTableBody').innerHTML = 
                '<tr><td colspan="9" class="error">加载产品数据失败</td></tr>';
        }
    }

    // 渲染产品表格
    renderProductsTable() {
        const tbody = document.getElementById('productsTableBody');
        
        if (this.currentProducts.length === 0) {
            tbody.innerHTML = '<tr><td colspan="9" class="no-data">暂无产品数据</td></tr>';
            return;
        }

        // 分页处理
        const startIndex = (this.currentPage - 1) * this.pageSize;
        const endIndex = startIndex + this.pageSize;
        const pageProducts = this.currentProducts.slice(startIndex, endIndex);

        const rows = pageProducts.map(product => {
            const isSelected = this.selectedProducts.has(product.id);
            const statusBadge = this.getStatusBadge(product.status);
            
            return `
                <tr ${isSelected ? 'class="selected"' : ''}>
                    <td>
                        <input type="checkbox" value="${product.id}" 
                               ${isSelected ? 'checked' : ''} 
                               onchange="app.toggleProductSelection(${product.id})">
                    </td>
                    <td>${product.productCode || '-'}</td>
                    <td>
                        <a href="#" onclick="app.showProductDetail(${product.id})" class="product-link">
                            ${product.productName || '-'}
                        </a>
                    </td>
                    <td>${product.category || '-'}</td>
                    <td>${this.formatCurrency(product.price)}</td>
                    <td>
                        <span class="stock-value ${this.getStockClass(product.stock, product.minStock)}">
                            ${product.stock || 0}
                        </span>
                    </td>
                    <td>${statusBadge}</td>
                    <td>${this.formatDate(product.createTime)}</td>
                    <td>
                        <div class="action-buttons">
                            <button class="btn btn-sm btn-primary" onclick="app.editProduct(${product.id})" title="编辑">
                                <i class="fas fa-edit"></i>
                            </button>
                            <button class="btn btn-sm btn-info" onclick="app.showProductDetail(${product.id})" title="详情">
                                <i class="fas fa-eye"></i>
                            </button>
                            <button class="btn btn-sm btn-danger" onclick="app.deleteProduct(${product.id})" title="删除">
                                <i class="fas fa-trash"></i>
                            </button>
                        </div>
                    </td>
                </tr>
            `;
        }).join('');

        tbody.innerHTML = rows;
    }

    // 获取状态徽章
    getStatusBadge(status) {
        switch (status) {
            case 'active':
                return '<span class="status-badge status-active">在产</span>';
            case 'inactive':
                return '<span class="status-badge status-inactive">停产</span>';
            default:
                return '<span class="status-badge status-unknown">未知</span>';
        }
    }

    // 获取库存状态类名
    getStockClass(stock, minStock) {
        if (!minStock) return '';
        if (stock <= minStock) return 'low-stock';
        if (stock <= minStock * 2) return 'medium-stock';
        return 'high-stock';
    }

    // 更新统计信息
    updateStatistics() {
        document.getElementById('totalProductCount').textContent = this.currentProducts.length;
        
        const categories = [...new Set(this.currentProducts.map(p => p.category).filter(c => c))];
        document.getElementById('categoryCount').textContent = categories.length;
        
        const totalStock = this.currentProducts.reduce((sum, p) => sum + (p.stock || 0), 0);
        document.getElementById('totalStock').textContent = totalStock;
        
        const totalValue = this.currentProducts.reduce((sum, p) => sum + ((p.price || 0) * (p.stock || 0)), 0);
        document.getElementById('totalValue').textContent = this.formatCurrency(totalValue);
    }

    // 搜索产品
    async searchProducts() {
        const keyword = document.getElementById('productSearch').value.trim();
        
        if (!keyword) {
            this.loadProducts();
            return;
        }

        try {
            const response = await this.apiCall(`/api/products/search?keyword=${encodeURIComponent(keyword)}`);
            this.currentProducts = response.data || [];
            this.currentPage = 1;
            this.renderProductsTable();
            this.updatePagination();
            this.updateStatistics();
        } catch (error) {
            console.error('搜索产品失败:', error);
        }
    }

    // 应用筛选
    async applyFilters() {
        const category = document.getElementById('categoryFilter').value;
        const status = document.getElementById('statusFilter').value;

        this.currentFilters = { category, status };

        try {
            let products = [];
            
            if (category) {
                const response = await this.apiCall(`/api/products/category/${encodeURIComponent(category)}`);
                products = response.data || [];
            } else {
                const response = await this.apiCall('/api/products');
                products = response.data || [];
            }

            // 应用状态筛选
            if (status) {
                products = products.filter(p => p.status === status);
            }

            this.currentProducts = products;
            this.currentPage = 1;
            this.renderProductsTable();
            this.updatePagination();
            this.updateStatistics();
        } catch (error) {
            console.error('筛选产品失败:', error);
        }
    }

    // 清除筛选
    clearFilters() {
        document.getElementById('productSearch').value = '';
        document.getElementById('categoryFilter').value = '';
        document.getElementById('statusFilter').value = '';
        this.currentFilters = {};
        this.loadProducts();
    }

    // 显示添加产品模态框
    showAddProductModal() {
        document.getElementById('modalTitle').textContent = '添加产品';
        document.getElementById('productForm').reset();
        this.showModal();
    }

    // 编辑产品
    async editProduct(productId) {
        try {
            const response = await this.apiCall(`/api/products/${productId}`);
            const product = response.data;
            
            if (!product) {
                this.showToast('产品不存在', 'error');
                return;
            }

            // 填充表单
            const form = document.getElementById('productForm');
            form.elements.productCode.value = product.productCode || '';
            form.elements.productName.value = product.productName || '';
            form.elements.category.value = product.category || '';
            form.elements.price.value = product.price || '';
            form.elements.stock.value = product.stock || '';
            form.elements.minStock.value = product.minStock || '';
            form.elements.description.value = product.description || '';
            form.elements.status.value = product.status || 'active';

            // 保存当前编辑的产品ID
            form.dataset.productId = productId;
            
            document.getElementById('modalTitle').textContent = '编辑产品';
            this.showModal();

        } catch (error) {
            console.error('加载产品信息失败:', error);
            this.showToast('加载产品信息失败', 'error');
        }
    }

    // 保存产品
    async saveProduct(formData) {
        try {
            const productData = Object.fromEntries(formData);
            const form = document.getElementById('productForm');
            const productId = form.dataset.productId;

            let response;
            if (productId) {
                // 更新产品
                response = await this.apiCall(`/api/products/${productId}`, {
                    method: 'PUT',
                    body: JSON.stringify(productData)
                });
                this.showToast('产品更新成功', 'success');
            } else {
                // 添加产品
                response = await this.apiCall('/api/products', {
                    method: 'POST',
                    body: JSON.stringify(productData)
                });
                this.showToast('产品添加成功', 'success');
            }

            this.hideModal();
            this.loadProducts();
            
        } catch (error) {
            console.error('保存产品失败:', error);
        }
    }

    // 删除产品
    async deleteProduct(productId) {
        if (!confirm('确定要删除这个产品吗？此操作不可恢复。')) {
            return;
        }

        try {
            await this.apiCall(`/api/products/${productId}`, {
                method: 'DELETE'
            });

            this.showToast('产品删除成功', 'success');
            this.selectedProducts.delete(productId);
            this.loadProducts();
            this.updateBatchActions();
            
        } catch (error) {
            console.error('删除产品失败:', error);
        }
    }

    // 显示产品详情
    async showProductDetail(productId) {
        try {
            const response = await this.apiCall(`/api/products/${productId}`);
            const product = response.data;
            
            if (!product) {
                this.showToast('产品不存在', 'error');
                return;
            }

            const detailContent = `
                <div class="product-detail">
                    <div class="detail-section">
                        <h4>基本信息</h4>
                        <div class="detail-grid">
                            <div class="detail-item">
                                <label>产品代码:</label>
                                <span>${product.productCode || '-'}</span>
                            </div>
                            <div class="detail-item">
                                <label>产品名称:</label>
                                <span>${product.productName || '-'}</span>
                            </div>
                            <div class="detail-item">
                                <label>分类:</label>
                                <span>${product.category || '-'}</span>
                            </div>
                            <div class="detail-item">
                                <label>价格:</label>
                                <span>${this.formatCurrency(product.price)}</span>
                            </div>
                            <div class="detail-item">
                                <label>库存:</label>
                                <span class="${this.getStockClass(product.stock, product.minStock)}">
                                    ${product.stock || 0}
                                </span>
                            </div>
                            <div class="detail-item">
                                <label>最小库存:</label>
                                <span>${product.minStock || '-'}</span>
                            </div>
                            <div class="detail-item">
                                <label>状态:</label>
                                <span>${this.getStatusBadge(product.status)}</span>
                            </div>
                            <div class="detail-item">
                                <label>创建时间:</label>
                                <span>${this.formatDate(product.createTime)}</span>
                            </div>
                        </div>
                    </div>
                    ${product.description ? `
                    <div class="detail-section">
                        <h4>产品描述</h4>
                        <p>${product.description}</p>
                    </div>
                    ` : ''}
                </div>
            `;

            document.getElementById('productDetailContent').innerHTML = detailContent;
            document.getElementById('productDetailModal').classList.add('show');
            
        } catch (error) {
            console.error('加载产品详情失败:', error);
            this.showToast('加载产品详情失败', 'error');
        }
    }

    // 工具函数
    formatCurrency(amount) {
        if (!amount) return '¥0.00';
        return `¥${parseFloat(amount).toFixed(2)}`;
    }

    formatDate(dateString) {
        if (!dateString) return '-';
        return new Date(dateString).toLocaleString('zh-CN');
    }

    showModal() {
        document.getElementById('productModal').classList.add('show');
    }

    hideModal() {
        document.getElementById('productModal').classList.remove('show');
        document.getElementById('productForm').reset();
        delete document.getElementById('productForm').dataset.productId;
    }

    hideDetailModal() {
        document.getElementById('productDetailModal').classList.remove('show');
    }

    showToast(message, type = 'info') {
        const toast = document.getElementById('toast');
        toast.textContent = message;
        toast.className = `toast ${type}`;
        toast.classList.add('show');
        
        setTimeout(() => {
            toast.classList.remove('show');
        }, 3000);
    }

    // 选择相关函数
    toggleProductSelection(productId) {
        if (this.selectedProducts.has(productId)) {
            this.selectedProducts.delete(productId);
        } else {
            this.selectedProducts.add(productId);
        }
        this.updateBatchActions();
        this.updateSelectAllCheckbox();
    }

    toggleSelectAll() {
        const selectAllCheckbox = document.getElementById('selectAll');
        const startIndex = (this.currentPage - 1) * this.pageSize;
        const endIndex = startIndex + this.pageSize;
        const pageProducts = this.currentProducts.slice(startIndex, endIndex);

        if (selectAllCheckbox.checked) {
            pageProducts.forEach(product => this.selectedProducts.add(product.id));
        } else {
            pageProducts.forEach(product => this.selectedProducts.delete(product.id));
        }

        this.renderProductsTable();
        this.updateBatchActions();
    }

    updateSelectAllCheckbox() {
        const selectAllCheckbox = document.getElementById('selectAll');
        const startIndex = (this.currentPage - 1) * this.pageSize;
        const endIndex = startIndex + this.pageSize;
        const pageProducts = this.currentProducts.slice(startIndex, endIndex);
        
        const selectedInPage = pageProducts.filter(product => this.selectedProducts.has(product.id));
        
        if (selectedInPage.length === 0) {
            selectAllCheckbox.checked = false;
            selectAllCheckbox.indeterminate = false;
        } else if (selectedInPage.length === pageProducts.length) {
            selectAllCheckbox.checked = true;
            selectAllCheckbox.indeterminate = false;
        } else {
            selectAllCheckbox.checked = false;
            selectAllCheckbox.indeterminate = true;
        }
    }

    updateBatchActions() {
        const batchActions = document.getElementById('batchActions');
        const selectedCount = document.getElementById('selectedCount');
        
        if (this.selectedProducts.size > 0) {
            batchActions.style.display = 'flex';
            selectedCount.textContent = this.selectedProducts.size;
        } else {
            batchActions.style.display = 'none';
        }
    }

    clearSelection() {
        this.selectedProducts.clear();
        this.renderProductsTable();
        this.updateBatchActions();
        this.updateSelectAllCheckbox();
    }

    // 分页相关函数
    updatePagination() {
        document.getElementById('pageStart').textContent = 
            this.currentProducts.length > 0 ? (this.currentPage - 1) * this.pageSize + 1 : 0;
        document.getElementById('pageEnd').textContent = 
            Math.min(this.currentPage * this.pageSize, this.totalItems);
        document.getElementById('totalItems').textContent = this.totalItems;

        // 更新分页按钮
        document.getElementById('prevBtn').disabled = this.currentPage <= 1;
        document.getElementById('nextBtn').disabled = this.currentPage >= this.totalPages;

        // 生成页码
        this.generatePageNumbers();
    }

    generatePageNumbers() {
        const pageNumbers = document.getElementById('pageNumbers');
        let html = '';

        const maxVisiblePages = 5;
        let startPage = Math.max(1, this.currentPage - Math.floor(maxVisiblePages / 2));
        let endPage = Math.min(this.totalPages, startPage + maxVisiblePages - 1);

        if (endPage - startPage + 1 < maxVisiblePages) {
            startPage = Math.max(1, endPage - maxVisiblePages + 1);
        }

        for (let i = startPage; i <= endPage; i++) {
            html += `
                <button class="btn btn-sm ${i === this.currentPage ? 'btn-primary' : 'btn-secondary'}" 
                        onclick="app.goToPage(${i})">${i}</button>
            `;
        }

        pageNumbers.innerHTML = html;
    }

    goToPage(page) {
        if (page >= 1 && page <= this.totalPages) {
            this.currentPage = page;
            this.renderProductsTable();
            this.updatePagination();
            this.updateSelectAllCheckbox();
        }
    }

    previousPage() {
        if (this.currentPage > 1) {
            this.goToPage(this.currentPage - 1);
        }
    }

    nextPage() {
        if (this.currentPage < this.totalPages) {
            this.goToPage(this.currentPage + 1);
        }
    }
}

// 全局函数
function showAddProductModal() {
    window.app.showAddProductModal();
}

function searchProducts() {
    window.app.searchProducts();
}

function clearFilters() {
    window.app.clearFilters();
}

function hideModal() {
    window.app.hideModal();
}

function hideDetailModal() {
    window.app.hideDetailModal();
}

function toggleSelectAll() {
    window.app.toggleSelectAll();
}

function batchEdit() {
    window.app.showToast('批量编辑功能开发中...', 'info');
}

function batchDelete() {
    if (window.app.selectedProducts.size === 0) {
        window.app.showToast('请先选择要删除的产品', 'warning');
        return;
    }
    
    if (confirm(`确定要删除选中的 ${window.app.selectedProducts.size} 个产品吗？`)) {
        window.app.showToast('批量删除功能开发中...', 'info');
    }
}

function clearSelection() {
    window.app.clearSelection();
}

function exportProducts() {
    window.app.showToast('导出功能开发中...', 'info');
}

function sortTable(column) {
    window.app.showToast('排序功能开发中...', 'info');
}

function previousPage() {
    window.app.previousPage();
}

function nextPage() {
    window.app.nextPage();
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    window.app = new ProductsApp();
});